import React, { useEffect, useMemo, useState } from 'react'
import { Input, Button } from 'antd-mobile'
import styles from './message.module.css'
import { PictureOutline,SmileOutline } from 'antd-mobile-icons'

//1.声明用户Id 和 服务 Id
const user_id = 1;
const server_id = 2222;

const ws = new WebSocket(
  `ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
)

function Index() {


  const [message, setMessage] = useState('')
  const [chat1, setChat] = useState([])
  useEffect(() => {
    ws.onopen = () => {
      console.log('连接成功')
      ws.send(JSON.stringify({ type: 'getChatList' }))
    }
    ws.onmessage = (msg) => {
      // console.log(msg.data)
      const { type, data } = JSON.parse(msg.data)
      console.log(type, data)
      if (type === 'getChatList') {
        setChat(data)
      }
      else if (type === 'addMessage') {
        setChat((pre) => [...pre, data])
      }
    }
  }, [])

  const handelAdd = () => {
    ws.send(
      JSON.stringify({
        type: 'addMessage',
        data: {
          user_id,
          server_id,
          message
        }
      })
    )
    setMessage('')
  }

  //图片
  const handelTp = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.click()

    input.onchange = (e) => {
      const file = e.target.files[0]
      const filereader = new FileReader()
      filereader.onload = () => {
        ws.send(
          JSON.stringify({
            type: 'addMessage',
            data: {
              user_id,
              server_id,
              message:e.target
            }
          })
        )
      }
    }
  }

  return (
    <div className={styles.lt}>
      {/* 内容 */}
      <div className={styles.ltlist}>
        {
          chat1.map((item, index) => {
            const chatItem = `chat-list-item-${item.dir === 1 ? 'right' : 'left'}`
            const avatar = item.dir === 1 ? item.user_avatar : item.server_avatar

            return (
              <div className={styles[chatItem]} key={index} >
                <div>
                  <img src={avatar} className={styles.tp} />
                </div>
                <div className={styles.text}>{item.message}</div>
              </div>
            )
          })
        }
      </div>
      {/* 发送 */}
      <div className={styles.fs}>
        <Input
          style={{ marginLeft: '10px' }}
          placeholder='请输入内容'
          value={message}
          onChange={val => {
            setMessage(val)
          }}
        />
        <Button color='primary' fill='solid' size='mini' onClick={() => handelAdd()}>
          发送
        </Button>
        <Button color='' fill='solid' size='mini' onClick={() => handelTp()}>
          <PictureOutline color='black' />
        </Button>
        <Button color='' fill='solid' size='mini' onClick={() => handelTp()}>
          <SmileOutline  color='black' />
        </Button>
      </div>
    </div>
  )
}

export default Index
